package com.sptpc.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.sptpc.pojo.Article;
import com.sptpc.pojo.Cart;
import com.sptpc.pojo.User;
import com.sptpc.service.ArticleService;
import com.sptpc.service.CartService;
import com.sptpc.util.Page;

@Controller("cartController")
public class CartController {
	
	@Autowired
	ArticleService articleService;
	@Autowired
	CartService cartService;
	
	@RequestMapping("/buy.action")
	public String getCart(String id,String buyNum,HttpServletRequest req,HttpServletResponse resp) {
		User user = (User)req.getSession().getAttribute("session_user");
		if(user == null) {
			return "login";
		}
		System.out.println("id="+id);
		System.out.println("buyNum="+buyNum);
		System.out.println(user.getUid());
		Article article = articleService.getArticleById(id);
		int a = cartService.addCart(article.getTitle(),buyNum,user.getUid());
		return "redirect:ShowShopCarItem.action";
	}
	
	@RequestMapping("/ShowShopCarItem.action")
	public String getAllCart(String currentPage,HttpServletRequest req,HttpServletResponse resp) {
		User user = (User)req.getSession().getAttribute("session_user");
		if(user == null) {
			return "login";
		}
		Page page = new Page();
		page.setTotalCount(cartService.cartCountByUid(user.getUid()));
		if(currentPage != null) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}
		page.setPageSize(3);
		
		List<Cart> cList = cartService.getCartByUid(user.getUid(),page.getCurrentPage(),page.getPageSize());
		req.setAttribute("shopCars", cList);
		req.setAttribute("page", page);
		return "shopCar";
	}
	
	@RequestMapping("/deleteCar.action")
	public String deleteCar(String cid) {
		cartService.deleteCar(Integer.parseInt(cid));
		return "redirect:ShowShopCarItem.action";
	}
}
